package com.bnz.dao.impl;

import com.bnz.dao.UserDao;
import com.bnz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


@Repository
public class UserDaoImpl implements UserDao,RowMapper<User> {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	// 查询所有用户
	@Override
	public List<User> findAll() {
		return jdbcTemplate.query("select * from user", this);
	}

	// 添加用户
	@Override
	public void add(User user) {
		jdbcTemplate.update("insert into user values(null,?,?)",user.getUsername(),user.getBalance());
	}

	//根据id查询单个记录
	@Override
	public User findById(int id) {
		return jdbcTemplate.queryForObject("select * from user where uid=?",this,id);
	}

	//4. 修改账户
	@Override
	public void update(User user) {
		jdbcTemplate.update("update user set username=?,balance=? where uid=?",
								user.getUsername(),
								user.getBalance(),
								user.getUid());
	}

	//根据id删除
	@Override
	public void delete(int id) {
		jdbcTemplate.update("delete from user where uid=?",id);
	}

	//行映射器
	@Override
	public User mapRow(ResultSet rs, int index) throws SQLException {
		return  new User(rs.getInt("uid"),
				rs.getString("username"),
				rs.getDouble("balance"));
	}
}
